﻿using Abp.Domain.Repositories;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Base;
using SportsPlatform.Dto.SportBusiness.CompetitionAchievementInfo;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Query.SportBusiness.CompetitionAchievementInfo;
using SportsPlatform.SportBusiness.ISportBusiness;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SportsPlatform.Consts;
using SportsPlatform.Jwt;
using SportsPlatform.Dto.SportBusiness.AchievementOverPointInfo;
using SportsPlatform.Dto.SportBusiness.AchievementPunishmentInfo;
using Abp.Application.Services;
using SportsPlatform.Enums;
using Abp.Collections.Extensions;
using SportsPlatform.Helpers;
using System.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using SportsPlatform.Global;
using SportsPlatform.SqlExecuter;

namespace SportsPlatform.SportBusiness.SportBusiness
{
    /// <summary>
    /// 赛事成绩信息表接口实现
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class CompetitionAchievementInfoService : SportsPlatformAppServiceBase, ICompetitionAchievementInfoService
    {
        //赛事成绩信息
        private readonly IRepository<CompetitionAchievementInfo, Guid> _competitionAchievementInfoRepository;

        //成绩过点记录信息
        private readonly IRepository<AchievementOverPointInfo, Guid> _achievementOverPointInfoRepository;

        //成绩惩罚记录信息
        private readonly IRepository<AchievementPunishmentInfo, Guid> _achievementPunishmentInfoRepository;

        //赛事项目信息
        private readonly IRepository<CompetitionProject, Guid> _competitionProjectRepository;

        //赛事信息
        private readonly IRepository<Competition, Guid> _competitionRepository;
        private readonly IWebHostEnvironment _webHostEnvironment;

        //项目表
        private readonly IRepository<Project, Guid> _projectRepository;
        private readonly IRepository<ProjectType, Guid> _projectTypeRepository;

        private readonly IRepository<CompetitionGroupingInfo, Guid> _groupRepository;
        private readonly IRepository<EventsSession, Guid> _eventRepository;

        private readonly IRepository<UserInfo, Guid> _userinfoRepository;
        private readonly IRepository<Employee, Guid> _employeeRepository;
        private readonly IRepository<CompeteTeam,Guid> _comteamRepository;

        private readonly ISqlExecuterRepository _sqlExecuterRepository;

        /// <summary>
        /// 构造方法
        /// </summary>
        public CompetitionAchievementInfoService(IWebHostEnvironment env,
            IRepository<CompetitionAchievementInfo, Guid> competitionAchievementInfoRepository,
            IRepository<AchievementOverPointInfo, Guid> achievementOverPointInfoRepository,
            IRepository<AchievementPunishmentInfo, Guid> achievementPunishmentInfoRepository,
            IRepository<UserInfo, Guid> userinfoRepository,
            IRepository<Employee, Guid> employeeRepository,
            IRepository<CompetitionGroupingInfo, Guid> groupRepository,
            IRepository<EventsSession, Guid> eventRepository,
            IRepository<CompeteTeam, Guid> comteamRepository,
            ISqlExecuterRepository sqlExecuterRepository,
            IRepository<CompetitionProject, Guid> competitionProjectRepository,
            IRepository<Project, Guid> projectRepository,
            IRepository<ProjectType, Guid> projectTypeRepository,
            IRepository<Competition, Guid> competitionRepository,
            IHttpContextAccessor context) : base(context)
        {
            _competitionAchievementInfoRepository = competitionAchievementInfoRepository;
            _achievementOverPointInfoRepository = achievementOverPointInfoRepository;
            _achievementPunishmentInfoRepository = achievementPunishmentInfoRepository;
            _competitionProjectRepository = competitionProjectRepository;
            _projectRepository = projectRepository;
            _webHostEnvironment = env;
            _projectTypeRepository = projectTypeRepository;
            _competitionRepository = competitionRepository;
            _userinfoRepository = userinfoRepository;
            _employeeRepository = employeeRepository;
            _sqlExecuterRepository = sqlExecuterRepository;
            _comteamRepository = comteamRepository;
            _groupRepository = groupRepository;
            _eventRepository = eventRepository;
        }

        /// <summary>
        /// 新增赛事成绩信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddCompetitionAchievementInfo(AddCompetitionAchievementInfoQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                CompetitionAchievementInfo competitionAchievementInfo = ObjectMapper.Map<CompetitionAchievementInfo>(query);
                competitionAchievementInfo.CreateUserId = token.Id;
                competitionAchievementInfo.CreateTime = DateTime.Now;
                await _competitionAchievementInfoRepository.InsertAsync(competitionAchievementInfo);
                baseResultDto.IsSuccess = true;
                baseResultDto.Message = "添加成功";
                baseResultDto.Code = HttpResultCode.Success;
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 赛事成绩信息同步
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> AchievementInfoSynchronization(List<AchievementInfoSynchronizationQuery> query)
        {
            BaseResultDto resultDto = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                //同步之前删除之前项目Id的分组
                var querypunilist = query
                    .GroupBy(group => new { group.CompetitionProjectId })
                    .Select(group => group.FirstOrDefault())
                    .ToList();
                querypunilist.ForEach(item =>
                {
                    var sql = "UPDATE T_B_CompetitionAchievementInfo SET IsDeleted=1,DeleteTime='" + DateTime.Now + "',DeleteUserId='" + token.Id + "' where CompetitionProjectId='" + item.CompetitionProjectId + "'";
                    _sqlExecuterRepository.Execute(sql, null);
                });
                var userlist = await _userinfoRepository.GetAllListAsync();
                var emplist = await _employeeRepository.GetAllListAsync();
                var comteamlist = await _comteamRepository.GetAllListAsync();
                var comlist = await _competitionRepository.GetAllListAsync();
                var comprojectlist = await _competitionProjectRepository.GetAllListAsync();
                var grouplist = await _groupRepository.GetAllListAsync();
                var eventlist = await _eventRepository.GetAllListAsync();
                var achilist = await _competitionAchievementInfoRepository.GetAllListAsync();
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Fail;
                foreach (var item in query)
                {
                    #region 数据验证
                    if (item.EmployeeId == null && item.CompeteTeamId == null)
                    {
                        resultDto.Message += $"参赛用户Id和参赛团队Id不能同时为空！";
                        continue;
                    }
                    if (item.EmployeeId != null && emplist.FirstOrDefault(info => info.Id == item.EmployeeId) == null)
                    {
                        resultDto.Message += $"参赛用户Id:{item.EmployeeId}不存在;";
                        continue;
                    }
                    if (item.CompeteTeamId != null && comteamlist.FirstOrDefault(info => info.Id == item.CompeteTeamId) == null)
                    {
                        resultDto.Message += $"参赛团队Id:{item.CompeteTeamId}不存在;";
                        continue;
                    }
                    if (comlist.FirstOrDefault(info => info.Id == item.CompetitionId) == null)
                    {
                        resultDto.Message += $"赛事Id:{item.CompetitionId}不存在;";
                        continue;
                    }
                    if (comprojectlist.FirstOrDefault(info => info.Id == item.CompetitionProjectId) == null)
                    {
                        resultDto.Message += $"赛事项目Id:{item.CompetitionProjectId}不存在;";
                        continue;
                    }
                    if (grouplist.FirstOrDefault(info => info.Id == item.CompetitionGroupingId) == null)
                    {
                        resultDto.Message += $"赛事项目分组信息Id:{item.CompetitionGroupingId}不存在;";
                        continue;
                    }
                    if (eventlist.FirstOrDefault(info => info.Id == item.EventsSessionId) == null)
                    {
                        resultDto.Message += $"场次分组信息Id:{item.EventsSessionId}不存在;";
                        continue;
                    }
                    #endregion
                    //如果id不存在就新建,否则就更新
                    var info = item.Id == null ? null : achilist.FirstOrDefault(info => info.Id == item.Id);
                    if (info == null)
                    {
                        var achiinfo = ObjectMapper.Map<CompetitionAchievementInfo>(item);
                        achiinfo.Id = item.Id ?? Guid.NewGuid();
                        if (item.CreateTime == null)
                        {
                            achiinfo.CreateTime = DateTime.Now;
                        }
                        if (item.CreateUserId == null)
                        {
                            achiinfo.CreateUserId = token.Id;
                        }
                        await _competitionAchievementInfoRepository.InsertAsync(achiinfo);
                    }
                    else
                    {
                        info.EmployeeId = item.EmployeeId ?? null;
                        info.CompeteTeamId = item.CompeteTeamId ?? null;
                        info.CompetitionId = item.CompetitionId;
                        info.CompetitionName = item.CompetitionName;
                        info.CompetitionProjectId = item.CompetitionProjectId;
                        info.CompetitionProjectName = item.CompetitionProjectName;
                        info.CompetitionGroupingId = item.CompetitionGroupingId;
                        info.EventsSessionId = item.EventsSessionId;
                        info.EventsSessionName = item.EventsSessionName;
                        info.CompetitionNode = item.CompetitionNode;
                        info.ContestantOrTeam = item.ContestantOrTeam;
                        info.SensorNumbers = item.SensorNumbers;
                        info.CompetitionNumberPosition = item.CompetitionNumberPosition;
                        info.AchievementCircle = item.AchievementCircle ?? 0;
                        info.AchievementTime = item.AchievementTime;
                        info.ActualLap = item.ActualLap ?? 0;
                        info.BuckleRing = item.BuckleRing;
                        info.BuckleTime = item.BuckleTime;
                        info.MissingMark = item.MissingMark ?? 0;
                        info.YellowCard = item.YellowCard ?? 0;
                        info.RedCard = item.RedCard ?? 0;
                        info.Score = item.Score ?? 0;
                        info.CompetitionRanking = item.CompetitionRanking ?? 0;
                        info.CompetitionStartTime = item.CompetitionStartTime ?? null;
                        info.CompetitionEndTime = item.CompetitionEndTime ?? null;
                        info.CreateTime = item.CreateTime ?? DateTime.Now;
                        info.CreateUserId = item.CreateUserId ?? token.CreateUserId;
                        info.IsDeleted = item.IsDeleted ?? false;
                        info.UpdateTime = null;
                        info.UpdateUserId = null;
                        info.DeleteTime = null;
                        info.DeleteUserId = null;
                        await _competitionAchievementInfoRepository.UpdateAsync(info);
                    }
                    resultDto.IsSuccess = true;
                    resultDto.Code = HttpResultCode.Success;
                }
                resultDto.Message = string.IsNullOrEmpty(resultDto.Message) ? "操作成功！" : resultDto.Message;
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 下载分页获取场次赛事成绩信息Excel
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<DownloadEventsSessionCompetitionAchievementDto>> DownloadEventsSessionCompetitionAchievementExcel(GetEventsSessionCompetitionAchievementInfoPageQuery query)
        {
            ResultDto<DownloadEventsSessionCompetitionAchievementDto> result = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);


                if (!query.EventsSessionId.IsNullAndEmpty())
                {
                    var competitionAchievementListInfo = await _competitionAchievementInfoRepository.GetAllListAsync(info => info.EventsSessionId == query.EventsSessionId);
                    var competitionAchievementInfo = competitionAchievementListInfo.OrderByDescending(info => info.CompetitionRanking)
                         .Skip((query.PageIndex - 1) * query.PageSize)
                         .Take(query.PageSize)
                         .ToList();

                    if (competitionAchievementInfo != null && competitionAchievementInfo.Count > 0)
                    {
                        result.IsSuccess = true;
                        result.Code = HttpResultCode.Success;
                        result.Message = "查询成功！";

                        DataTable dataTable = new DataTable();
                        dataTable.Columns.Add("排名");
                        dataTable.Columns.Add("参赛者/团队");
                        dataTable.Columns.Add("比赛号位");
                        dataTable.Columns.Add("成绩圈");
                        dataTable.Columns.Add("成绩时");
                        dataTable.Columns.Add("实际跑圈");
                        dataTable.Columns.Add("扣圈");
                        dataTable.Columns.Add("罚时");
                        dataTable.Columns.Add("漏标");
                        dataTable.Columns.Add("黄牌");
                        dataTable.Columns.Add("红牌");
                        competitionAchievementInfo.ForEach(info =>
                        {
                            DataRow row = dataTable.NewRow();
                            row["排名"] = info.CompetitionRanking == null ? "" : info.CompetitionRanking.ToString();
                            row["参赛者/团队"] = info.ContestantOrTeam == null ? "" : info.ContestantOrTeam.ToString();
                            row["比赛号位"] = info.CompetitionNumberPosition == null ? "" : info.CompetitionNumberPosition.ToString();
                            row["成绩圈"] = info.AchievementCircle == null ? "" : info.AchievementCircle.ToString();
                            row["成绩时"] = info.AchievementTime == null ? "" : info.AchievementTime.ToString();
                            row["实际跑圈"] = info.ActualLap == null ? "" : info.ActualLap.ToString();
                            row["扣圈"] = info.BuckleRing == null ? "" : info.BuckleRing.ToString();
                            row["罚时"] = info.BuckleTime == null ? "" : info.BuckleTime.ToString();
                            row["漏标"] = info.MissingMark == null ? "" : info.MissingMark.ToString();
                            row["黄牌"] = info.YellowCard == null ? "" : info.YellowCard.ToString();
                            row["红牌"] = info.RedCard == null ? "" : info.RedCard.ToString();
                            dataTable.Rows.Add(row);
                        });
                        result.Data = new DownloadEventsSessionCompetitionAchievementDto() { Url = ExportHelper.DataTableToExcel(_webHostEnvironment, dataTable, "项目成绩") };
                    }
                    else
                    {
                        result.IsSuccess = false;
                        result.Code = HttpResultCode.SqlError;
                        result.Message = "未查询到该场次成绩信息！";
                    }

                }
                else
                {

                    var competitionAchievementInfolist = (await _competitionAchievementInfoRepository.GetAllListAsync())
                  .WhereIf(query.CompetitionId != null, info => info.CompetitionId == query.CompetitionId)
                  .WhereIf(query.CompetitionProjectId != null, info => info.CompetitionProjectId == query.CompetitionProjectId)
                  .WhereIf(query.EventsSessionId != null, info => info.EventsSessionId == query.EventsSessionId)
                  .WhereIf(!(string.IsNullOrEmpty(query.KeywordName)), info => info.CompetitionName.Contains(query.KeywordName) || info.CompetitionProjectName.Contains(query.KeywordName) || info.ContestantOrTeam.Contains(query.KeywordName))
                  .WhereIf(token.CompanyId != null, info => _competitionRepository.FirstOrDefault(info.CompetitionId).Merchants == token.CompanyId)
                  .ToList();

                    var competitionAchievementInfopage = competitionAchievementInfolist.OrderByDescending(info => info.CreateTime)
                       .Skip((query.PageIndex - 1) * query.PageSize)
                       .Take(query.PageSize)
                      .ToList();

                    DataTable dataTable = new DataTable();
                    dataTable.Columns.Add("参赛者/团队");
                    dataTable.Columns.Add("赛事名称");
                    dataTable.Columns.Add("比赛项目");
                    dataTable.Columns.Add("项目类型");
                    dataTable.Columns.Add("比赛类型");
                    dataTable.Columns.Add("比赛号位");
                    dataTable.Columns.Add("比赛节点");
                    dataTable.Columns.Add("成绩圈");
                    dataTable.Columns.Add("成绩时");
                    dataTable.Columns.Add("实际跑圈");
                    dataTable.Columns.Add("扣圈");
                    dataTable.Columns.Add("扣时");
                    dataTable.Columns.Add("漏标");
                    dataTable.Columns.Add("黄牌");
                    dataTable.Columns.Add("红牌");
                    dataTable.Columns.Add("成绩得分");
                    dataTable.Columns.Add("比赛排名");
                    dataTable.Columns.Add("比赛时间");
                    dataTable.Columns.Add("比赛地点");
                    if (competitionAchievementInfopage != null && competitionAchievementInfopage.Count > 0)
                    {
                        var competitionAchievementInfoDtolist = ObjectMapper.Map<List<CompetitionAchievementInfoDto>>(competitionAchievementInfopage);

                        competitionAchievementInfoDtolist.ForEach(dto =>
                        {
                            var competitionProjectinfo = _competitionProjectRepository.FirstOrDefault(info => info.Id == dto.CompetitionProjectId);
                            var projectinfo = _projectRepository.FirstOrDefault(info => info.Id == competitionProjectinfo.ProjectId);
                            dto.ProjectTypeName = (_projectTypeRepository.FirstOrDefault(info => info.Id == projectinfo.ProjectTypeID)).Name;
                            dto.GameTypeName = Enum.GetName(typeof(CompetitionProjectTypeEnum), competitionProjectinfo.GameType);
                            dto.CompetitionVenue = competitionProjectinfo.DetailsAddress;


                            DataRow row = dataTable.NewRow();
                            row["参赛者/团队"] = dto.ContestantOrTeam;
                            row["赛事名称"] = dto.CompetitionName;
                            row["比赛项目"] = dto.CompetitionProjectName;
                            row["项目类型"] = dto.ProjectTypeName;
                            row["比赛类型"] = dto.GameTypeName;
                            row["比赛号位"] = dto.CompetitionNumberPosition;
                            row["比赛节点"] = dto.CompetitionNode;
                            row["成绩圈"] = dto.AchievementCircle;
                            row["成绩时"] = dto.AchievementTime;
                            row["实际跑圈"] = dto.ActualLap;
                            row["扣圈"] = dto.BuckleRing;
                            row["扣时"] = dto.BuckleTime;
                            row["黄牌"] = dto.YellowCard;
                            row["红牌"] = dto.RedCard;
                            row["成绩得分"] = dto.Score;
                            row["比赛排名"] = dto.CompetitionRanking;
                            row["比赛时间"] = dto.CompetitionStartTime.ToString("yyyy-MM-dd") + "至" + dto.CompetitionEndTime.ToString("MM-dd HH:mm:ss");
                            row["比赛地点"] = dto.CompetitionVenue;
                            dataTable.Rows.Add(row);
                        });
                    }
                    result.Data = new DownloadEventsSessionCompetitionAchievementDto() { Url = ExportHelper.DataTableToExcel(_webHostEnvironment, dataTable, "项目成绩") };
                }
            }
            catch (Exception e)
            {
                result.IsSuccess = false;
                result.Code = HttpResultCode.Error;
                result.Message = e.Message.ToString();
            }
            return result;
        }

        /// <summary>
        /// 下载分页获取场次赛事成绩信息PDF
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<DownloadEventsSessionCompetitionAchievementDto>> DownloadEventsSessionCompetitionAchievementPDF(GetEventsSessionCompetitionAchievementInfoPageQuery query)
        {
            ResultDto<DownloadEventsSessionCompetitionAchievementDto> result = new();
            try
            {
                if (query.EventsSessionId == Guid.Empty)
                {
                    result.IsSuccess = false;
                    result.Code = HttpResultCode.Fail;
                    result.Message = "未传入EventsSessionId比赛项目场次Id！";
                    return result;
                }
                var competitionAchievementListInfo = await _competitionAchievementInfoRepository.GetAllListAsync(info => info.EventsSessionId == query.EventsSessionId);
                var competitionAchievementInfo = competitionAchievementListInfo.OrderByDescending(info => info.CompetitionRanking)
                     .Skip((query.PageIndex - 1) * query.PageSize)
                     .Take(query.PageSize)
                     .ToList();
                if (competitionAchievementInfo != null && competitionAchievementInfo.Count > 0)
                {
                    result.IsSuccess = true;
                    result.Code = HttpResultCode.Success;
                    result.Message = "查询成功！";
                    result.Data.Url = "";
                }
                else
                {
                    result.IsSuccess = false;
                    result.Code = HttpResultCode.SqlError;
                    result.Message = "未查询到该场次成绩信息！";
                }
            }
            catch (Exception e)
            {
                result.IsSuccess = false;
                result.Code = HttpResultCode.Error;
                result.Message = e.Message.ToString();
            }
            return result;
        }

        /// <summary>
        /// 分页获取赛事成绩信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<CompetitionAchievementInfoDto>> GetCompetitionAchievementInfo(GetCompetitionAchievementInfoQuery query)
        {
            PagePagingDto<CompetitionAchievementInfoDto> pagePagingDto = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);
                var competitionAchievementInfolist = (await _competitionAchievementInfoRepository.GetAllListAsync())
                    .WhereIf(query.CompetitionId != null, info => info.CompetitionId == query.CompetitionId)
                    .WhereIf(query.CompetitionProjectId != null, info => info.CompetitionProjectId == query.CompetitionProjectId)
                    .WhereIf(query.EventsSessionId != null, info => info.EventsSessionId == query.EventsSessionId)
                    .WhereIf(!(string.IsNullOrEmpty(query.KeywordName)), info => info.CompetitionName.Contains(query.KeywordName) || info.CompetitionProjectName.Contains(query.KeywordName) || info.ContestantOrTeam.Contains(query.KeywordName))
                    .WhereIf(token.CompanyId != null, info => _competitionRepository.FirstOrDefault(info.CompetitionId).Merchants == token.CompanyId)
                    .ToList();

                var competitionAchievementInfopage = competitionAchievementInfolist.OrderByDescending(info => info.CreateTime)
                   .Skip((query.PageIndex - 1) * query.PageSize)
                   .Take(query.PageSize)
                  .ToList();
                if (competitionAchievementInfopage != null && competitionAchievementInfopage.Count > 0)
                {
                    pagePagingDto.IsSuccess = true;
                    pagePagingDto.Code = HttpResultCode.Success;
                    pagePagingDto.TotalCount = competitionAchievementInfolist.Count;
                    pagePagingDto.TotalPage = competitionAchievementInfolist.Count % query.PageSize == 0 ? competitionAchievementInfolist.Count / query.PageSize : competitionAchievementInfolist.Count / query.PageSize + 1;
                    var competitionAchievementInfoDtolist = ObjectMapper.Map<List<CompetitionAchievementInfoDto>>(competitionAchievementInfopage);
                    competitionAchievementInfoDtolist.ForEach(dto =>
                    {
                        var competitionProjectinfo = _competitionProjectRepository.FirstOrDefault(info => info.Id == dto.CompetitionProjectId);
                        var projectinfo = _projectRepository.FirstOrDefault(info => info.Id == competitionProjectinfo.ProjectId);
                        dto.ProjectTypeName = (_projectTypeRepository.FirstOrDefault(info => info.Id == projectinfo.ProjectTypeID)).Name;
                        dto.GameTypeName = Enum.GetName(typeof(CompetitionProjectTypeEnum), competitionProjectinfo.GameType);
                        dto.CompetitionVenue = competitionProjectinfo.DetailsAddress;
                    });
                    pagePagingDto.Data = competitionAchievementInfoDtolist;
                    pagePagingDto.Message = "查询成功";
                }
                else
                {
                    pagePagingDto.IsSuccess = false;
                    pagePagingDto.Code = HttpResultCode.SqlError;
                    pagePagingDto.Message = "未查询到该场次成绩信息！";
                }
            }
            catch (Exception e)
            {
                pagePagingDto.IsSuccess = false;
                pagePagingDto.Code = HttpResultCode.Error;
                pagePagingDto.Message = e.Message.ToString();
            }
            return pagePagingDto;
        }

        /// <summary>
        /// 分页获取场次赛事成绩信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<EventsSessionCompetitionAchievementInfoDto>> GetEventsSessionCompetitionAchievementInfo(GetEventsSessionCompetitionAchievementInfoPageQuery query)
        {
            PagePagingDto<EventsSessionCompetitionAchievementInfoDto> pagePagingDto = new();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);


                if (query.EventsSessionId == Guid.Empty)
                {
                    pagePagingDto.IsSuccess = false;
                    pagePagingDto.Code = HttpResultCode.Fail;
                    pagePagingDto.Message = "未传入EventsSessionId比赛项目场次Id！";
                    return pagePagingDto;
                }
                var competitionAchievementListInfo = await _competitionAchievementInfoRepository.GetAllListAsync(info => info.EventsSessionId == query.EventsSessionId);
                var competitionAchievementInfo = competitionAchievementListInfo.OrderByDescending(info => info.CompetitionRanking)
                     .Skip((query.PageIndex - 1) * query.PageSize)
                     .Take(query.PageSize)
                     .ToList();
                if (competitionAchievementInfo != null && competitionAchievementInfo.Count > 0)
                {
                    pagePagingDto.IsSuccess = true;
                    pagePagingDto.Code = HttpResultCode.Success;
                    pagePagingDto.TotalCount = competitionAchievementListInfo.Count;
                    pagePagingDto.TotalPage = competitionAchievementListInfo.Count % query.PageSize == 0 ? competitionAchievementListInfo.Count / query.PageSize : competitionAchievementListInfo.Count / query.PageSize + 1;
                    pagePagingDto.Data = ObjectMapper.Map<List<EventsSessionCompetitionAchievementInfoDto>>(competitionAchievementInfo);
                    pagePagingDto.Message = "查询成功";
                }
                else
                {
                    pagePagingDto.IsSuccess = false;
                    pagePagingDto.Code = HttpResultCode.SqlError;
                    pagePagingDto.Message = "未查询到该场次成绩信息！";
                }
            }
            catch (Exception e)
            {
                pagePagingDto.IsSuccess = false;
                pagePagingDto.Code = HttpResultCode.Error;
                pagePagingDto.Message = e.Message.ToString();
            }
            return pagePagingDto;
        }

        /// <summary>
        /// 获取场次赛事成绩信息详情
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ResultDto<EventsSessionCompetitionAchievementInfoDetailsDto>> GetEventsSessionCompetitionAchievementInfoDetails(GetEventsSessionCompetitionAchievementInfoQuery query)
        {
            ResultDto<EventsSessionCompetitionAchievementInfoDetailsDto> resultDto = new();
            try
            {
                //ToKen判断
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                if (query.Id == Guid.Empty)
                {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.Message = "未传入赛事成绩Id！";
                    return resultDto;
                }

                var competitionAchievementInfo = await _competitionAchievementInfoRepository.FirstOrDefaultAsync(query.Id);
                if (competitionAchievementInfo != null)
                {
                    var competitionProjectinfo = await _competitionProjectRepository.FirstOrDefaultAsync(info => info.Id == competitionAchievementInfo.CompetitionProjectId);

                    if (!competitionProjectinfo.IsNullAndEmpty())
                    {
                        var mapper = ObjectMapper.Map<EventsSessionCompetitionAchievementInfoDetailsDto>(competitionAchievementInfo);

                        var projectinfo = _projectRepository.FirstOrDefault(info => info.Id == competitionProjectinfo.ProjectId);

                        //项目类型
                        mapper.ProjectTypeName = (await _projectTypeRepository.FirstOrDefaultAsync(info => info.Id == projectinfo.ProjectTypeID)).Name;

                        //比赛类型
                        mapper.GameTypeName = Enum.GetName(typeof(CompetitionProjectTypeEnum), competitionProjectinfo.GameType);

                        //成绩过点记录信息
                        mapper.AchievementOverPointInfos = ObjectMapper.Map<List<AchievementOverPointInfoDto>>(await _achievementOverPointInfoRepository.GetAllListAsync(info => info.CompetitionAchievementId == query.Id));

                        //成绩惩罚记录信息
                        mapper.AchievementPunishmentInfos = ObjectMapper.Map<List<AchievementPunishmentInfoDto>>(await _achievementPunishmentInfoRepository.GetAllListAsync(info => info.CompetitionAchievementId == query.Id));

                        resultDto.IsSuccess = true;
                        resultDto.Code = HttpResultCode.Success;
                        resultDto.Data = mapper;
                        resultDto.Message = "查询成功";
                    }
                    else
                    {
                        resultDto.IsSuccess = false;
                        resultDto.Code = HttpResultCode.Fail;
                        resultDto.Message = "未查询到该场次下所属的项目信息";
                    }

                }
                else
                {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.Message = "未查询到相关数据！";
                }

            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 根据赛事ID获取赛事比赛项目Id和名称
        /// 用于查询条件下拉框
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetCompetionProjectListByCompetionIdDto>> GetCompetionProjectListByCompetionId([FromBody] GetCompetionProjectListByCompetionIdQuery query)
        {
            var res = new ResultListDto<GetCompetionProjectListByCompetionIdDto>();
            var project = await _competitionProjectRepository.GetAllListAsync(a => a.CompetitionId == query.Id && a.IsDeleted == false);
            if (project.Count > 0)
            {
                var list = new List<GetCompetionProjectListByCompetionIdDto>();
                var dto = new GetCompetionProjectListByCompetionIdDto();
                foreach (var item in project)
                {
                    dto = new GetCompetionProjectListByCompetionIdDto();
                    dto.Id = item.Id;
                    dto.Name = item.Name;
                    list.Add(dto);
                }
                res.Data = list;
                res.Code = HttpResultCode.Success;
                res.Count = project.Count;
                res.IsSuccess = true;
                res.Message = "查询成功";
            }
            else
            {
                res.Code = HttpResultCode.NotData;
                res.Count = 0;
                res.IsSuccess = true;
                res.Message = "未查询到数据";
            }
            return res;
        }

        /// <summary>
        /// 更新赛事成绩信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<BaseResultDto> UpdateCompetitionAchievementInfo(UpdateCompetitionAchievementInfoQuery query)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                //ToKen判断
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);
                CompetitionAchievementInfo competitionAchievementInfo = await _competitionAchievementInfoRepository.FirstOrDefaultAsync(info => info.Id == query.Id);
                if (query.AchievementCircle != null)
                {
                    competitionAchievementInfo.AchievementCircle = query.AchievementCircle;
                }
                if (!string.IsNullOrEmpty(query.AchievementTime))
                {
                    competitionAchievementInfo.AchievementTime = query.AchievementTime;
                }
                if (query.ActualLap != null)
                {
                    competitionAchievementInfo.ActualLap = query.ActualLap;
                }
                if (query.BuckleRing != null)
                {
                    competitionAchievementInfo.BuckleRing = query.BuckleRing;
                }
                if (!string.IsNullOrEmpty(query.BuckleTime))
                {
                    competitionAchievementInfo.BuckleTime = query.BuckleTime;
                }
                if (query.MissingMark != null)
                {
                    competitionAchievementInfo.MissingMark = query.MissingMark;
                }
                if (query.YellowCard != null)
                {
                    competitionAchievementInfo.YellowCard = query.YellowCard;
                }
                if (query.RedCard != null)
                {
                    competitionAchievementInfo.RedCard = query.RedCard;
                }
                if (query.Score != null)
                {
                    competitionAchievementInfo.Score = query.Score;
                }
                if (query.CompetitionRanking != null)
                {
                    competitionAchievementInfo.CompetitionRanking = query.CompetitionRanking;
                }
                await _competitionAchievementInfoRepository.UpdateAsync(competitionAchievementInfo);
                baseResultDto.IsSuccess = true;
                baseResultDto.Code = HttpResultCode.Success;
                baseResultDto.Message = "更新成功";
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }

            return baseResultDto;
        }
    }
}
